<template>
  <div class="app-container">
    <el-card class="box-card search-div" v-show="showSearch">
        <el-form :inline="true" :model="listQuery" ref="queryForm">
            <el-form-item label="字典码">
            <el-input v-model="listQuery.code" :maxlength="20"   clearable></el-input>
            </el-form-item>
           <el-form-item label="字典名称">
            <el-input v-model="listQuery.dictValue" :maxlength="20"   clearable></el-input>
            </el-form-item>
             <el-form-item label="状态">
            <el-select v-model="listQuery.status" clearable style="width: 100%;"> <el-option v-for="dict in statusOptions" :key="dict.dictKey" :label="dict.dictValue" :value="dict.dictKey" /></el-select>
            </el-form-item>
         <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
         <el-button @click="handleResetQuery" icon="el-icon-refresh">重置</el-button>
     </el-form>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" v-hasPermi="['dict_sysDict_add']" class="el-icon-plus" @click="add">新增</el-button>
        <el-button type="danger" class="el-icon-delete" @click="cleanCache">更新缓存</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
      <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row height="246px" @row-click="loadChildList">
        <el-table-column label="序号" type="index" min-width="5%"/>
        <el-table-column align="center" label="字典码" prop="code"></el-table-column>
        <el-table-column align="center" label="字典名称" prop="dictValue"></el-table-column>
        <el-table-column align="center" label="字典备注" prop="remark"></el-table-column>
        <el-table-column align="center" label="修改时间" prop="updateTime" width="150px"></el-table-column>
        <el-table-column align="center" label="状态" prop="status" width="80px">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0">正常</el-tag>
            <el-tag v-if="scope.row.status==1" type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button plain v-hasPermi="['dict_sysDict_edit']" type="violet" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button plain v-hasPermi="['dict_sysDict_add']" type="primary" @click="handleAddChild(scope.$index, scope.row)">添加字典项</el-button>
            <el-dropdown @command="handleCommand" trigger="click" style="margin-left: 10px;">
              <el-button>
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="'0_'+scope.row.id" v-hasPermi="['config_sysConfig_enable']" v-if="scope.row.status==0">禁用</el-dropdown-item>
                <el-dropdown-item :command="'1_'+scope.row.id" v-hasPermi="['config_sysConfig_enable']" v-if="scope.row.status==1">启用</el-dropdown-item>
                <el-dropdown-item :command="'2_'+scope.row.id" v-hasPermi="['dict_sysDict_remove']" >删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </el-card>
   <el-card class="box-card">
      <div slot="header" class="clearfix">
          <span>{{parentDictName}}字典项</span>
      </div>
    <el-table :data="childList" border fit highlight-current-row>
      <el-table-column label="序号" type="index" min-width="5%"/>
        <el-table-column align="center" label="字典名称" prop="dictValue"></el-table-column>
        <el-table-column align="center" label="字典值" prop="dictKey"></el-table-column>
        <el-table-column align="center" label="字典备注" prop="remark"></el-table-column>
        <el-table-column align="center" label="修改时间" prop="updateTime" width="150px"></el-table-column>
        <el-table-column align="center" label="状态" prop="status" width="80px">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0">正常</el-tag>
            <el-tag v-if="scope.row.status==1" type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button plain v-hasPermi="['dict_sysDict_edit']" type="violet" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button plain v-hasPermi="['dict_sysDict_remove']" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
     </el-card>
    <!--弹出框-->
    <el-dialog :title="dialogTitle" :width="'600px'" :visible.sync="showDialog" :close-on-click-modal="false">
      <el-form :rules="rules" ref="savesysDictData" :model="savesysDictData" label-width="100px">
        <el-form-item label="字典码:" prop="code" v-if="addParent">
            <el-input v-model="savesysDictData.code" :maxlength="20"  placeholder="最多输入20个字符" clearable show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="字典名称:" prop="dictValue">
            <el-input v-model="savesysDictData.dictValue" :maxlength="20"  placeholder="最多输入20个字符" clearable show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="字典值:" prop="dictKey" v-if="addChild">
            <el-input  v-model="savesysDictData.dictKey" :maxlength="20"  placeholder="最多输入20个字符" clearable show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="排序:" prop="orderNum">
            <el-input-number v-model="savesysDictData.orderNum" :min="0" :max="999999" style="width: 100%;"></el-input-number>
        </el-form-item>
        <el-form-item label="字典备注:" prop="remark">
            <el-input type="textarea" rows="3" v-model="savesysDictData.remark" :maxlength="255"  placeholder="最多输入255个字符" clearable show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave('savesysDictData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as sysDict from './js/dict'
import { mapGetters } from 'vuex'

export default {
  name: 'dictList',
  data() {
    return {
      list: null,
      childList: null,
      // 遮罩层
      listLoading: true,
      childListLoading: false,
      // 当前选择父
      parentId: null,
      parentDictName:null,
      addChild: false,
      addParent: true,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      listQuery: {page: 1, limit: 5,     code: '',    dictValue: '',      status: '' },
      statusOptions:[],
      showDialog: false,
      savesysDictData: {  id: '',  parentId: '',  code: '',  dictKey: '',  dictValue: '',  orderNum: '',  remark: '',  status: ''},
      rules: {
        id: [{ required: true, message: '请输入主键', trigger: 'blur' }],
        parentId: [{ required: true, message: '请输入父主键', trigger: 'blur' }],
        code: [{ required: true, message: '请输入字典码', trigger: 'blur' }],
        dictKey: [{ required: true, message: '请输入字典值', trigger: 'blur' }],
        dictValue: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
        orderNum: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      dialogTitle: '添加系统字典'
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  created() {
    this.init()
    this.getList()
  },
  methods: {
    init(){
      this.getDictByCode("data_status").then(response => {
        this.statusOptions = response.data;
      })
    },
    getList() { // 获取所有系统字典
      this.listLoading = true
      sysDict.list(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
        this.parentId = null
        this.parentDictName = null
        this.childList = []
      })
    },
    getChildList(parentId){
      sysDict.childList(parentId).then(response => {
        this.childList = response.data
      })
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleResetQuery(){
      this.listQuery = {page: 1, limit: 5}
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    loadChildList(row){
      this.parentId = row.id
      this.parentDictName = '【'+row.dictValue+'】'
      this.getChildList(row.id)
    },
    handleCommand(c){
      const command = c.split('_')
      if (command[0] === '0') {
        this.handleStatus(command[1],0)
      } else if (command[0] === '1'){
        this.handleStatus(command[1],1)
      } else if (command[0] === '2'){
        this.handleDelete(command[1])
      }
    },
    // 启/禁用
    handleStatus(id, type) {
      var status = 1
      var msg = '请确定是否禁用该数据?'
      if (type === 1) {
        status = 0; msg = '请确定是否启用该数据?'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        sysDict.updateStatusById(id, status).then((response) => {
          this.$message({ type: 'success', message: '操作成功!' })
          this.getList()
        })
      }).catch(function(error) { console.log(error) })
    },
    //删除
    handleDelete(id) {
      this.$confirm('请确定是否删除该数据', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        sysDict.removeByIds(id).then((response) => {
          this.$message({ type: 'success', message: '操作成功!' })
          this.getList()
        })
      }).catch(function(error) { console.log(error) })
    },
    // 新增
    add(pit, index) {
      this.showDialog = true
      this.dialogTitle = '添加系统字典'
      // 清空表单数据
      this.$nextTick(() => {
        this.resetForm('savesysDictData')
        this.savesysDictData.parentId = 0
        this.savesysDictData.id=null
        this.savesysDictData.dictKey=-1
      })
    },
    // 编辑
    handleEdit(index, row) {
      if(row.parentId==0){
        this.addChild = false
        this.addParent = true
      }else{
        this.addChild = true
        this.addParent = false
      }
      this.showDialog = true
      this.dialogTitle = '编辑系统字典'
      this.$nextTick(() => {
        this.resetForm('savesysDictData')
        // 需要拷贝一下，不然会清空列表
        let tmpRow = JSON.parse(JSON.stringify(row));
        this.savesysDictData = tmpRow
      })
    },
    // 添加字典项
    handleAddChild(index,row){
      this.addChild = true
      this.addParent = false
      this.showDialog = true
      this.dialogTitle = '添加系统字典'
      // 清空表单数据
      this.$nextTick(() => {
        this.resetForm('savesysDictData')
        this.savesysDictData.parentId = row.id
        this.savesysDictData.id=null
        this.savesysDictData.code=row.code
      })
    },
    // 清理缓存
    cleanCache(){
      sysDict.cleanCache().then((response) => {
        this.$message({type: 'success',message: '操作成功!'})
        this.getList()
      }).catch(function(error) {
            console.log(error)
      })
    },
    // 保存
    onSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          sysDict.editSave(this.savesysDictData).then((response) => {
            this.$message({ type: 'success', message: '操作成功!' })
            this.getList()
          	this.showDialog = false
          }).catch(function(error) {
            console.log(error)
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.pagination-container {
	position: relative;
	height: 25px;
  margin: 10px;
}
.pagination-container .el-pagination {
	right: 0;
	position: absolute;
}
.pagination-container.hidden {
  display: none;
}
</style>
